package org.lifei.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.lifei.exception.BusinessException;
import org.lifei.exception.LifeiAssert;
import org.lifei.exception.ResponseCode;
import org.lifei.gift.constants.UserConstants;
import org.lifei.gift.domain.User;
import org.lifei.gift.mapper.UserMapper;
import org.lifei.gift.service.IUserService;
import org.lifei.gift.service.IVerifyCodeService;
import org.lifei.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void userRegisterSendSms(String phone) {
        //1、验证电话号码是否被注册
        User user = userService.selectOne(new EntityWrapper<User>().eq("phone", phone));
        LifeiAssert.isNull(user, ResponseCode.RESPONSE_CODE_400005);


        //生成一个验证码
        String code = VerifyCodeUtils.generateVerifyCode(6, "1234567890");
        //去redis里查看验证码是否过期
        String key = UserConstants.USER_REGISTER_SEND_SMS_KEY+ "-"+phone;
        Object codeInRedis = redisTemplate.opsForValue().get(key);
        if (codeInRedis!=null){
            //证明当前手机号已经发送过验证码，还没有过期
            //1.使用当前的时间-上一次发送的时间<60s 就是不合法的请求--报错
            String codeInredisStr = codeInRedis.toString();
            code = codeInredisStr.split(":")[0];
            Long preTime = Long.valueOf(codeInredisStr.split(":")[1]);
            if (System.currentTimeMillis()-preTime<60*1000){
                throw  new BusinessException(ResponseCode.RESPONSE_CODE_400008);
            }
            //如果过了重发时间，就要将这个验证码重新发一遍
        }

        //去redis里过去当前的手机号是否已经发送过验证码并且没有过期
        //3、发送到用户手机
        System.out.println("手机验证码为："+code);
        //4、把手机号存起来--后续在提交用户的时候验证
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);

    }
}
